package Netty.scoketDemo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author caihe
 * @date 2021/7/5 16:59
 */
public class NIOServer {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        List<SocketChannel> socketChannelList = new ArrayList<>();
        // 为java设置的非阻塞的类
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress(8080));
            // 设置为非阻塞
            serverSocketChannel.configureBlocking(false);
            while (true) {
                SocketChannel channel = serverSocketChannel.accept();
                if (channel == null) {
                    //表示没人连接
                    System.out.println("正在等待客户端请求连接...");
                    Thread.sleep(500);
                } else {
                    System.out.println("当前接收到客户端请求连接...");
                    socketChannelList.add(channel);
                }

                for (SocketChannel socketChannel : socketChannelList) {
                    // 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    int read = socketChannel.read(buffer);
                    if (read != 0) {
                        // 切换模式 写-》读
                        buffer.flip();
                        String content = Charset.forName("utf-8").decode(buffer).toString();
                        System.out.println("接受到消息： " + content);
                        buffer.clear();
                                
                    }else {
                        System.out.println("当前未收到客户端消息");
                    }
                }
                
//                if (channel != null) {
//                    serverSocketChannel.configureBlocking(false);
//                    // 切换模式 写-》读
//                    buffer.flip();
//                    int effective = channel.read(buffer);
//                    if (effective != 0) {
//                        System.out.println(Charset.forName("utf-8").decode(buffer).toString());
//                    } else {
//                        System.out.println("当前未收到客户端消息");
//                    }
//                }

            }

        } catch (Exception e) {

        }


    }

}
